package com.xjj.sso.server.rabbitmq;

import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.xjj.sso.server.util.SSOConfiguration;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;


public abstract class EndPoint {
	
	protected Channel channel;
    protected Connection connection;
    protected String endPointName;
    private static ConnectionFactory factory;
    
    
    //mq config
    public  static String EXCHANGE_NAME;  
	private static String SERVER;
	private static int PORT;
	private static String USER_NAME;
	private static String PASSWORD;
     
    public EndPoint(String endpointName) throws IOException, TimeoutException{
         this.endPointName = endpointName;
         
         //初始化
         init();
         
         if(null == factory)
         {
        	//Create a connection factory
             factory = new ConnectionFactory();
             
             //hostname of your rabbitmq server
             factory.setHost(SERVER);
             factory.setPort(PORT);
             factory.setUsername(USER_NAME);
             factory.setPassword(PASSWORD);
             
         }
         
         //factory.setVirtualHost("vhost001");
         
         //getting a connection
         connection = factory.newConnection();
         
         //creating a channel
         channel = connection.createChannel();
         
         //声明交换机（exchange），默认的 类型是 direct
         
         //declaring a queue for this channel. If queue does not exist,
         //it will be created on the server.
         //参数依次是：队列名，是否持久化，是否排外(即：专有)，是否自动删除，
         //channel.queueDeclare(endpointName, true, false, false, null);
    }
     
     
    /**
     * 关闭channel和connection。并非必须，因为隐含是自动调用的。
     * @throws IOException
     * @throws TimeoutException 
     */
     public void close() throws IOException, TimeoutException{
         this.channel.close();
         this.connection.close();
     }
     
     /**
      * 初始化参数
      */
     private void init(){
    	 
    	if(null == SERVER || null == EXCHANGE_NAME)
    	{
    		try {
    			SERVER = SSOConfiguration.get("rabbitmq.server");
        		EXCHANGE_NAME = SSOConfiguration.get("rabbitmq.exchange");
    			PORT = Integer.parseInt(SSOConfiguration.get("rabbitmq.port"));
        		USER_NAME = SSOConfiguration.get("rabbitmq.username");
        		PASSWORD = SSOConfiguration.get("rabbitmq.password");
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
 	}
}
